package com.nuorui.common.listener;

import com.nuorui.common.utils.SmartIpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.context.logging.LoggingApplicationListener;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

/**
 * 初始化IP工具类
 *
 * @author Fred
 */
@Slf4j
@Order(value = LoggingApplicationListener.DEFAULT_ORDER)
public class Ip2RegionListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {

    private static final String IP_FILE_NAME = "ip2region.xdb";

    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        try {
            // 1. 从classpath加载ip2region.xdb资源流
            ClassPathResource resource = new ClassPathResource(IP_FILE_NAME);

            // 2. 在系统临时目录创建一个临时文件
            Path tempFile = Files.createTempFile("ip2region-", ".xdb");

            // 3. 复制资源流内容到临时文件（覆盖写入）
            Files.copy(resource.getInputStream(), tempFile, StandardCopyOption.REPLACE_EXISTING);

            // 4. 初始化ip2region，传入临时文件路径
            SmartIpUtil.init(tempFile.toAbsolutePath().toString());

            // 5. JVM退出时删除临时文件（可选）
            tempFile.toFile().deleteOnExit();

        } catch (IOException e) {
            log.error("无法复制ip数据文件 ip2region.xdb", e);
            throw new ExceptionInInitializerError("无法复制ip数据文件");
        }
    }
}